package com.leet.code.thread;

import java.util.function.IntConsumer;

public class Code1116 {
    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(100);
        new Thread(() -> {
            try {
                zeroEvenOdd.zero(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                zeroEvenOdd.odd(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                zeroEvenOdd.even(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }


    static class ZeroEvenOdd {
        private int n;

        public ZeroEvenOdd(int n) {
            this.n = n;
        }

        int a = 0;

        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                while (a != 0) {
                    Thread.yield();
                }
                printNumber.accept(0);
                a = i % 2 + 1;
            }
        }

        public void even(IntConsumer printNumber) throws InterruptedException {

            for (int i = 2; i <= n; i += 2) {
                while (a != 2) {
                    Thread.yield();
                }
                printNumber.accept(i);
                a = 0;
            }


        }

        public void odd(IntConsumer printNumber) throws InterruptedException {
            for (int i = 1; i <= n; i += 2) {
                while (a != 1) {
                    Thread.yield();
                }
                printNumber.accept(i);
                a = 0;
            }

        }
    }


}
